/**
 * @a https://leetcode.cn/problems/number-of-enclaves/
 */

#include "../../common.h"


class Solution
{
    vector<vector<bool>> vis; // 1 refer to visited, 2 refer to visited && escapable
public:
    int numEnclaves(vector<vector<int>> &grid)
    {
        const static int dx[4] = {0, 0, 1, -1};
        const static int dy[4] = {1, -1, 0, 0};
        // 正难则反
        int row = grid.size(), col = grid[0].size();
        vis.resize(row, vector <bool>(col, false));
        queue<pair<int, int>> que;
        for (int i = 0; i < col; ++i)
        {
            if (grid[0][i] == 1)
            {
                que.push({0, i});
                vis[0][i] = true;
            }
            if (grid[row - 1][i] == 1)
            {
                que.push({row - 1, i});
                vis[row - 1][i] = true;
            }
        }
        for (int i = 1; i < row - 1; ++i)
        {
            if (grid[i][0] == 1)
            {
                que.push({i, 0});
                vis[i][0] = true;
            }
            if (grid[i][col - 1] == 1)
            {
                que.push({i, col - 1});
                vis[i][col - 1] = true;
            }
        }

        while (que.size())
        {
            int sz = que.size();

            auto [a, b] = que.front();
            que.pop();
            for (int i = 0; i < 4; ++i)
            {
                int x = a + dx[i], y = b + dy[i];
                if (x >= 0 && x < row && y >= 0 && y < col && vis[x][y] == false && grid[x][y] == 1)
                {
                    que.push({x, y});
                    vis[x][y] = true;
                }
            }
        }
        int ret = 0;
        for (int i = 0; i < row; ++i)
        {
            for (int j = 0; j < col; ++j)
            {
                if (grid[i][j] == 1 && vis[i][j] == false)
                    ++ret;
            }
        }
        return ret;
    }
};

